package cn.hhchat.kit.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created this one by HMH on 2017/3/21.
 */
public class XmlUtil {

    final static Logger logger = LoggerFactory.getLogger(XmlUtil.class);

    public static String getXMLAttribution(String xmlString,String attrName) {
        String value = null;
        try {
            Document document = DocumentHelper.parseText(xmlString);
            value = document.getRootElement().element(attrName).getStringValue();
            return value;
        } catch (DocumentException e) {
            logger.error(e.getMessage());
            return "Xml解析失败";
        }
    }

    public static Map<String, String> xmlToMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();
        InputStream ins = null;
        try {
            ins = request.getInputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Document doc = null;
        try {
            doc = reader.read(ins);
        } catch (DocumentException e1) {
            e1.printStackTrace();
        }
        if (doc == null) {
            throw new NullPointerException("xml doc 对象不存在");
        }
        Element root = doc.getRootElement();

        @SuppressWarnings("unchecked")
        List<Element> list = root.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
        try {
            ins.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return map;
    }

    public static String genCdataAttr(String text) {
        return "<![CDATA[" + text + "]]>";
    }

}
